package wsp.dailymarket.shopping;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.ArrayDataModel;
import javax.faces.model.DataModel;
import javax.sql.DataSource;
import wsp.dailymarket.auth.AuthenticationBean;

/**
 * Represents a list of invoices that belong to a particular customer
 * @author Matt
 */
@ManagedBean(name = "invoiceListBean")
@RequestScoped
public class InvoiceListBean {

	@Resource(name = "jdbc/dmderby")
	private DataSource ds;
	@ManagedProperty(value = "#{authenticationBean}")
	private AuthenticationBean authBean;
	private ArrayList<InvoiceBean> invoiceList;

	public InvoiceListBean() {
		invoiceList = new ArrayList<InvoiceBean>();
	}

	public boolean getRenderInvoiceList() {
		invoiceList.clear();
		try {
			Connection conn = null;
			try {
				conn = ds.getConnection();
				Statement stmt = conn.createStatement();
				String sql = "SELECT * FROM APP.ORDERS WHERE CLIENT_ID = '" + authBean.getAuthentication().getUserID() + "'";
				ResultSet rs = stmt.executeQuery(sql);
				while (rs.next()) {
					InvoiceBean newInvoice = new InvoiceBean();
					newInvoice.populate(
							rs.getInt("ID"),
							rs.getTimestamp("TS_PLACED"),
							rs.getInt("ORDER_STATUS"));
					invoiceList.add(newInvoice);
				}
			} finally {
				if (conn != null) {
					conn.close();
				}
			}
		} catch (SQLException ex) {
			ex.printStackTrace(System.err);
			FacesMessage msg = new FacesMessage();
			msg.setSeverity(FacesMessage.SEVERITY_FATAL);
			msg.setSummary("Database Error!");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}
		return !this.invoiceList.isEmpty();
	}

	public DataModel<InvoiceBean> getInvoiceList() {
		return new ArrayDataModel(invoiceList.toArray());
	}

	public void setAuthBean(AuthenticationBean newValue) {
		this.authBean = newValue;
	}

	public boolean getRenderable() {
		return !this.invoiceList.isEmpty();
	}
}
